package wrapper

import (
	"context"
	"git.multiverse.io/eventkit/common/util"
	"git.multiverse.io/eventkit/dxc-server/config"
	"git.multiverse.io/eventkit/dxc-server/models"
	"git.multiverse.io/eventkit/kit/constant"
	"git.multiverse.io/eventkit/kit/contexts"
)

type Wrapper struct{}

func (c *Wrapper) Before(ctx context.Context, request interface{}, opts interface{}) context.Context {
	// generate a new span ID
	dxcContext := models.DxcContextFromCtx(ctx)

	if dxcContext == nil {
		return ctx
	}

	spanID := util.GenerateSerialNo(
		config.Cfg.Service.Org,
		config.Cfg.Service.Wks,
		config.Cfg.Service.Env,
		config.Cfg.Service.Su,
		config.Cfg.InstanceId,
		constant.SpanIDType)

	ctx, handlerContexts := contexts.BuildContextFromParent(ctx)

	handlerContexts.With(
		contexts.Span(
			contexts.BuildSpanContexts(
				contexts.TraceID(dxcContext.SpanCtx.TraceID),
				contexts.SpanID(spanID),
				contexts.ParentSpanID(dxcContext.SpanCtx.ParentSpanID),
			),
		),
	)

	return contexts.BuildContextFromParentWithHandlerContexts(ctx, handlerContexts)
}

func (c *Wrapper) After(ctx context.Context, request interface{}, response interface{}, opts interface{}) context.Context {
	return ctx
}
